package ru.volgogradetzzz.utils 
{
	import flash.system.ApplicationDomain;
	import flash.utils.Dictionary;
	import ru.volgogradetzzz.net.SequentialSwfLoader;
	/**
	 * ...
	 * @author Volgogradetzzz
	 */
	public class LibraryExplorer 
	{
		private const _LOADER:SequentialSwfLoader = SequentialSwfLoader.getInstance();
		private const _LOGGER:Logger = Logger.getInstance();
		private const _OBJECTS_BY_NAME:Dictionary = new Dictionary();
		
		private static var instance:LibraryExplorer;
		
		public static function getInstance():LibraryExplorer 
		{
			if (!instance)
			{
				instance = new LibraryExplorer(SINGLETON_KEY);
			}
			
			return instance;
		}
		
		public function LibraryExplorer(checkKey:Object) 
		{
			if (checkKey != SINGLETON_KEY)
			{
				throw(new Error("Экземпляр LibraryExplorer необходимо получать с помощью метода LibraryExplorer.getInstance()."));
			}
		}
		
		public function getObject(library:String, className:String, createNew:Boolean = false):*
		{
			if (!createNew)
			{
				if (_OBJECTS_BY_NAME[library + '_' + className])
				{
					return _OBJECTS_BY_NAME[library + '_' + className];
				}
			}
			
			var appDomain:ApplicationDomain = _LOADER.getApplicationDomain(library);
			
			if (appDomain)
			{
				if (appDomain.hasDefinition(className))
				{
					var obj:Object;
					
					if (createNew)
					{
						obj = new (appDomain.getDefinition(className) as Class)();
						if (!_OBJECTS_BY_NAME[library + '_' + className])
						{
							_OBJECTS_BY_NAME[library + '_' + className] = obj;
						}
					}
					else
					{
						obj = new (appDomain.getDefinition(className) as Class)();
						_OBJECTS_BY_NAME[library + '_' + className] = obj;
					}
					
					
					return obj;
				}
				else
				{
					_LOGGER.log('Application domain ' + library + ' не имеет класса ' + className + '.', Logger.ERROR);
					return null;
				}
			}
			
			_LOGGER.log('Application domain ' + library + ' не найден.', Logger.ERROR);
			return null;
		}
	}
}

internal const SINGLETON_KEY:Object = {};